package com.tarena.demo.luban.all.main.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.demo.luban.all.main.service.CartService;
import com.tarena.demo.luban.commons.exception.BusinessDemoException;
import com.tarena.demo.luban.commons.restful.JsonResult;
import com.tarena.demo.luban.commons.restful.ResponseCode;
import com.tarena.demo.luban.protocol.cart.param.CartAddParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/base/cart")
@Api(tags = "购物车")
public class CartController {
    // 控制层装配业务逻辑层对象
    @Autowired
    private CartService cartService;
    @PostMapping("/add")
    @ApiOperation("新增购物车中的商品")
    public JsonResult cartAdd(CartAddParam cartAddParam){
        Entry entry = null;
        try {
            entry = SphU.entry("cartAdd");
            cartService.cartAdd(cartAddParam);
            return JsonResult.ok("新增购物车完成!");
        } catch (BlockException e) {
            log.info("sentinel对新增购物车限流");
            //可以看作是降级处理
            return JsonResult.failed(new BusinessDemoException(ResponseCode.BAD_REQUEST,"限流了"));
        }catch (Exception e) {
            log.error("系统不明异常");
            return JsonResult.failed(ResponseCode.BAD_REQUEST,e.getMessage());
        } finally {
            if (entry!=null){
                entry.exit();
            }
        }
    }
}
